package main

import (
	"fmt"
	"github.com/urfave/cli"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

var Version = "v0.1"

func main() {

	app := cli.NewApp()
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "work-dir",
			Usage: "working fir for concurrent test.",
			Value: ".",
		},
		cli.StringFlag{
			Name:  "oldaddress",
			Usage: "oldaddress should be replace with the new one.",
			Value: "xxxxxxx",
		},
		cli.IntFlag{
			Name:  "num",
			Usage: "number of test cases",
			Value: 20,
		},
	}
	app.Action = StartMain
	app.Name = "fprepare"
	app.Version = Version
	err := app.Run(os.Args)
	if err != nil {
		os.Exit(-1)
	}
}

func StartMain(ctx *cli.Context) {

	workdir := ctx.String("work-dir")
	oldaddress := ctx.String("oldaddress")
	os.Chdir(workdir)

	fmt.Printf("Current Working Direcotry: %s\n", workdir)

	address, err := ioutil.ReadFile("address.txt")
	if err != nil {
		log.Fatalln(err)
	}

	address_lines := strings.Split(string(address), "\n")

	num := ctx.Int("num")

	for i:= 0; i <  num; i++ {

		fmt.Printf("now process: %s\n", filepath.Join(workdir, strconv.Itoa(i), "dnc.json"))

		content_replace(filepath.Join(workdir, strconv.Itoa(i), "dnc.json"), oldaddress,address_lines[i])

	}
}

func content_replace(filename string, old string, new string) {

	read, err := ioutil.ReadFile(filename)
	if err != nil {
		panic(err)
	}

	newContents := strings.Replace(string(read), old, new, -1)

	err = ioutil.WriteFile(filename, []byte(newContents), 0)
	if err != nil {
		panic(err)
	}
}

